<template>
  <div>
    <VForm
      ref="vformComponents"
      :form="formData.form"
      :options="formData.options"
      :rules="formData.rules"
      :labelWidth="formData.labelWidth"
      :rowspan="rowspan"
      @changeAddress="changeAddress"
      @changeGdArea="changeGdArea"
      @toLoadMethods="toLoadMethods"
    ></VForm>
    <div class="e-dialog-footer">
      <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button v-if="openType != 'detail'" type="primary" @click="sure">确 定</el-button>
    </span>
    </div>
  </div>
</template>

<script>
  import {
    riskHazardDetail,
    riskHazardUpdate,
    riskHazardAdd
  } from '@/api/risk/riskHazard'
  import { treeDataChild} from '@/api/risk/treeData'
  import { alarmFacilityList} from '@/api/alarm/facility'
  import VForm from "@/components/VForm/index";

  export default {
    components: {
      VForm,
    },
    props: {
      width: {
        type: String,
        default: "70%",
      },
      title: {
        type: String,
        default: "详情",
      },
      id: {},
      openType: {
        type: String,
        default: "add"
      },
      dialogVisible: {
        type: Boolean,
        default: false
      }
    },
    watch: {
      'width': {
        handler(newVal, oldVal) {
          console.log('newVal===', newVal, oldVal)
          let w = this.width.split('%')[0]
          if (w >= 60) {
            this.rowspan = 2
          } else {
            this.rowspan = 1
          }
        },
        deep: true,
        immediate: true
      },
      'bClassifyOptions': {
        handler(newVal, oldVal) {
          this.formData.options.forEach(t => {
            if (t.key == 'bclassify') {
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'sClassifyOptions': {
        handler(newVal, oldVal) {
          this.formData.options.forEach(t => {
            if (t.key == 'sclassify') {
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'categoryOptions': {
        handler(newVal, oldVal) {
          this.formData.options.forEach(t => {
            if (t.key == 'category') {
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'gradeOptions': {
        handler(newVal, oldVal) {
          this.formData.options.forEach(t => {
            if (t.key == 'grade') {
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'stateOptions': {
        handler(newVal, oldVal) {
          this.formData.options.forEach(t => {
            if (t.key == 'state') {
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'facilityOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='facilityId'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      dialogVisible:{
        handler(newVal, oldVal) {
          if(newVal){
            console.log("监测指===",newVal)
            this.getData()
          }
        },
        deep: true,
        immediate: true
      },
      openType:{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t => {
            if(t.key!='bclassify' && t.key!='sclassify'){
              t.disabled = newVal == 'detail' ? true : false
            }


          })
        },
        deep: true,
        immediate: true
      }
    },
    computed: {
      isVisible: {
        get() {
          return this.dialogVisible
        },
        set() {
          this.close()
        }
      }
    },
    data() {
      return {
        rowspan: 1,
        dict: {},
        formData: {
          form: {
            flagCode: "1",
            reportTime: "",
            name: "",
            bclassify: "",

            sclassify: "",
            category: "",
            address: "",
            memo: "",
            grade: "",
            state: "",
            reportName: "",
            reportContact: "",
            handleUnit: "",
            handleName: "",
            acceptTime: "",
            handleMemo: "",
            handleTime: "",
            handleReport: [],
            sceneFile: [],
            objClassify: "",
            objName: "",
            lon: "",
            lat: "",
            provinceCode: "",
            cityCode: "",
            countyCode: "",
            areaCode: "",
            updateTime: "",
            updateBy: "",
            requireCompleteTime:"",
            reportUnit:"",
            img:[],
            discoveryTime:"",
            handleProcess:"",
            handleImg:[],
            mapData: {},
            fromType:'',

            facilityId:'',
            facilityName:'',

            //扩展字段
            extendJson: "",
            collapseLength: "",
            collapseWidth: "",
            collapseHeight: "",
            collapseAcreage: "",
            collapseVolume: "",
            collapseHd: "",
            disposalPhone: "",
          },
          options: [
            // {
            //   title: "标识码",
            //   key: "flagCode",
            //   type: "text",
            // },
            {
              title: "上报时间",
              key: "reportTime",
              type: "date",
              disabled: true
            },
            {
              title: "隐患名称",
              key: "name",
              type: "text",
            },
            {
              title: "隐患大类",
              key: "bclassify",
              type: "select",
              multiple: false,
              disabled: true,
              option: {
                data: this.bClassifyOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "name", // 指定value对应data的字段
                },
              },
            },
            {
              title: "隐患细类",
              key: "sclassify",
              type: "select",
              multiple: false,
              disabled: true,
              option: {
                data: this.sClassifyOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "name", // 指定value对应data的字段
                },
              },
            },

            {
              title: "三级类别",
              key: "category",
              type: "select",
              multiple: false,
              option: {
                data: this.categoryOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "name", // 指定value对应data的字段
                },
              },
            },

            {
              title: "设施名称",
              key: "facilityId",
              type: "select",
              multiple:false,
              event:'changeFacilityName',
              option: {
                data: this.facilityOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "name", // 指定value对应data的字段
                },
              },
            },

            {
              title: "隐患等级",
              key: "grade",
              type: "select",
              multiple: false,
              option: {
                data: this.gradeOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title: "上报单位",
              key: "reportUnit",
              type: "text",
            },
            {
              title: "上报人",
              key: "reportName",
              type: "text",
            },
            {
              title: "上报人电话",
              key: "reportContact",
              type: "text",
            },
            {
              title: "发现时间",
              key: "discoveryTime",
              type: "date",
            },


            {
              title: "隐患地址",
              type: 'mapPosition',
              key: 'mapData',
            },
            {
              title: "隐患描述",
              key: "memo",
              type: "textarea",
              columnWidth: 'w100'
            },

            {
              title: "隐患状态",
              key: "state",
              type: "select",
              multiple: false,
              option: {
                data: this.stateOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },


            {
              title: "坍塌长度",
              key: "collapseLength",
              type: "text",
            },
            {
              title: "坍塌宽度",
              key: "collapseWidth",
              type: "text",
            },
            {
              title: "坍塌高度",
              key: "collapseHeight",
              type: "text",
            },
            {
              title: "坍塌面积",
              key: "collapseAcreage",
              type: "text",
            },
            {
              title: "坍塌体积",
              key: "collapseVolume",
              type: "text",
            },
            {
              title: "覆土厚度",
              key: "collapseHd",
              type: "text",
            },

            {
              title: "现场照片",
              key: "sceneFile",
              type: "file",
              fileType: "file",
              listType: "text",
              uploadTextTip: "",
              columnWidth: 'w100'
            },
            {
              title: "处置信息",
              columnWidth: 'w100'
            },

            {
              title: "隐患处置过程",
              key: "handleMemo",
              type: "textarea",
              columnWidth: 'w100'
            },
            {
              title: "隐患处置单位",
              key: "handleUnit",
              type: "text",
            },
            {
              title: "处置负责人",
              key: "handleName",
              type: "text",
            },
            {
              title: "隐患受理时间",
              key: "acceptTime",
              type: "date",
            },
            {
              title: "要求整改完成时间",
              key: "requireCompleteTime",
              type: "date",
            },
            {
              title: "处置完成时间",
              key: "handleTime",
              type: "date",
            },
            {
              title: "处置负责人联系方式",
              key: "disposalPhone",
              type: "text",
            },
            {
              title: "隐患处置报告",
              key: "handleReport",
              type: "file",
              fileType: "file",
              listType: "text",
              uploadTextTip: ""
            },


          ],
          rules: {
            flagCode: [
              {max: 20, message: '长度最大为20个字符', trigger: 'blur'}
            ],
            reportTime: [
              {required: true, message: '请输入', trigger: 'blur'}
            ],
            discoveryTime:[
              {required: true, message: '请输入', trigger: 'blur'}
            ],
            name: [
              {required: true, message: '请输入', trigger: 'blur'},
              {max: 64, message: '长度最大为64个字符', trigger: 'blur'}
            ],
            bclassify: [
              {required: true, message: '请选择', trigger: 'blur'}
            ],
            sclassify: [
              {required: true, message: '请选择', trigger: 'blur'}
            ],
            category: [
              {required: true, message: '请选择', trigger: 'blur'}
            ],
            address: [
              {max: 200, message: '长度最大为200个字符', trigger: 'blur'}
            ],
            memo: [
              {required: true, message: '请输入', trigger: 'blur'},
              {max: 1024, message: '长度最大为1024个字符', trigger: 'blur'}
            ],
            grade: [
              {required: true, message: '请选择', trigger: 'blur'}
            ],
            state: [
              {required: true, message: '请选择', trigger: 'blur'}
            ],
            reportName: [
              {max: 50, message: '长度最大为50个字符', trigger: 'blur'}
            ],
            reportContact: [
              {max: 20, message: '长度最大为20个字符', trigger: 'blur'}
            ],
            handleUnit: [
              {max: 128, message: '长度最大为128个字符', trigger: 'blur'}
            ],
            handleName: [
              {max: 50, message: '长度最大为50个字符', trigger: 'blur'}
            ],
            acceptTime: [],
            handleMemo: [
              {max: 1024, message: '长度最大为1024个字符', trigger: 'blur'}
            ],
            handleTime: [],
            handleReport: [],
            sceneFile: [],
            lon: [
              {max: 36, message: '长度最大为36个字符', trigger: 'blur'}
            ],
            lat: [
              {max: 36, message: '长度最大为36个字符', trigger: 'blur'}
            ],
            provinceCode: [
              {max: 12, message: '长度最大为12个字符', trigger: 'blur'}
            ],
            cityCode: [
              {max: 12, message: '长度最大为12个字符', trigger: 'blur'}
            ],
            countyCode: [
              {max: 12, message: '长度最大为12个字符', trigger: 'blur'}
            ],
            areaCode: [
              {max: 12, message: '长度最大为12个字符', trigger: 'blur'}
            ],

          },
          labelWidth: "180px",
        },
        // 字典
        bClassifyOptions: [],
        sClassifyOptions: [],
        categoryOptions: [],
        gradeOptions: [],
        stateOptions: [],
        facilityOptions:[],
        extendJsonObject: {
          collapseLength: "",
          collapseWidth: "",
          collapseHeight: "",
          collapseAcreage: "",
          collapseVolume: "",
          collapseHd: "",
          disposalPhone: "",
        }
      };
    },
    methods: {

      toLoadMethods(methods){
        this[methods]();
      },

      initMap(data) {
        this.formData.form.mapData = {
          address: data.address,
          gpsX: data.lon,
          gpsY: data.lat,
          towncode: data.areaCode,
        };
      },

      changeFacilityName(){
        var label = this.facilityOptions.find(t=>t.name==this.formData.form.facilityId).label;
        this.formData.form.facilityName=label;
      },



      async sendCategoryData(){
        let queryData ={}
        queryData.name='hazardSClassify';
        queryData.code =this.formData.form.sclassify;
        let res =await treeDataChild(queryData);
        if(res.code==200) {
          let that = this
          res.data.forEach(function (item,index){
            var one ={}
            one.label= item.label;
            one.name=item.code;
            that.categoryOptions.push(one);
          })
        }
      },

      async sendFacilityData(){
        let queryData ={}
        queryData.modeType="ALARM_DLL";
        let res =await alarmFacilityList(queryData);
        if(res.code==200) {
          let that = this
          res.data.forEach(function (item,index){
            var one ={}
            one.label=item.name ;
            one.name=item.id;
            that.facilityOptions.push(one);
          })

        }


      },

      changeAddress(data) {
        console.log('changeAddress', data)
        this.formData.form.mapData = data
        this.formData.form.lon = data.gpsX
        this.formData.form.lat = data.gpsY
        this.formData.form.address = data.address

        this.formData.form.provinceCode = data.areaCode[0]
        this.formData.form.cityCode = data.areaCode[1]
        this.formData.form.countyCode = data.areaCode[2]
        this.formData.form.areaCode = data.towncode
      },
      changeGdArea(data) {
        console.log('changeGdArea', data)
        console.log(this.formData.form.areaCode_new)
      },
      getCountySubIndex(cityCode) {
        // 中山、东莞截取10位
        let filterList = ['442000000000', '441900000000']
        if (filterList.findIndex(t => t == cityCode) > -1) {
          return 10;
        }
        return 6;
      },
      positionSubmitFormat() {

        let mapData = this.formData.form.mapData
        console.log(">>>");
        console.log(mapData);
        if (mapData) {
          this.formData.form.lon = mapData.gpsX
          this.formData.form.lat = mapData.gpsY
          this.formData.form.address = mapData.address
          this.formData.form.areaCode = mapData.towncode
          if (mapData.towncode) {
            this.formData.form.provinceCode = mapData.towncode.substr(0, 2).padEnd(12, '0')
            this.formData.form.cityCode = mapData.towncode.substr(0, 4).padEnd(12, '0')
            let subIndex = this.getCountySubIndex(this.formData.form.cityCode)
            this.formData.form.countyCode = mapData.towncode.substr(0, subIndex).padEnd(12, '0')
          }
        }
      },
      positionLoadFormat() {
        let form = this.formData.form
        let mapData = {}


        mapData.address = form.address
        mapData.gpsX = parseFloat(form.lon)
        mapData.gpsY = parseFloat(form.lat)
        mapData.towncode = form.areaCode
        this.formData.form.mapData = mapData


        console.log("mpap", mapData)
      },


      submitFormat(){
        this.formData.form.sceneFile = JSON.stringify(this.formData.form.sceneFile);
        this.formData.form.handleReport = JSON.stringify(this.formData.form.handleReport);
        this.formData.form.img = JSON.stringify(this.formData.form.img);
        this.formData.form.handleImg = JSON.stringify(this.formData.form.handleImg);

      },
      loadFormat(){
          this.formData.form.sceneFile  = this.formData.form.sceneFile ? JSON.parse(this.formData.form.sceneFile) : [];
          this.formData.form.handleReport  = this.formData.form.handleReport ? JSON.parse(this.formData.form.handleReport) : [];
        if(this.formData.form.img!=null && this.formData.form.img!='' && this.formData.form.img!='null'){
          this.formData.form.img = JSON.parse( this.formData.form.img ).map(item=>{
            return{
              name:item.name,
              url: process.env.VUE_APP_BASE_API + 'file/api/download/'+item.fileId,
              uid: item.uuid,
              fileId: item.fileId,
            }
          })
        }else {
          this.formData.form.img = []
        }
        if(this.formData.form.handleImg!=null &&
          this.formData.form.handleImg!='' && this.formData.form.handleImg!='null'){
          this.formData.form.handleImg = JSON.parse( this.formData.form.handleImg ).map(item=>{
            return{
              name:item.name,
              url: process.env.VUE_APP_BASE_API + 'file/api/download/'+item.fileId,
              uid: item.uuid,
              fileId: item.fileId,
            }
          })
        }else {
          this.formData.form.handleImg = []
        }
      },
      getCheckBoxData(value, option, type) {
        if (type == "submit") {
          if (value.length == 0) {
            return null
          }
          let temp = [];
          value.forEach(t => {
            let item = option.find(x => x.label == t)
            if (item != undefined) {
              temp.push(item.value)
            }
          })
          return temp.join(",")
        } else {
          if (!value) {
            return []
          } else {
            let data = value.split(",")
            let temp = []
            data.forEach(t => {
              let item = option.find(x => x.value == t)
              if (item != undefined) {
                temp.push(item.label)
              }
            })
            return temp
          }
        }
      },
      sure() {
        console.log('sure===', this.formData.form)
        this.$refs.vformComponents.$refs.form.validate().then(res => {
          this.submitFormat()
          if (this.openType == "add") {
            this.add()
          } else {
            this.update()
          }
        })
      },
      addExtendJson() {
        this.extendJsonObject.collapseAcreage = this.formData.form.collapseAcreage
        this.extendJsonObject.collapseVolume = this.formData.form.collapseVolume
        this.extendJsonObject.collapseHd = this.formData.form.collapseHd
        this.extendJsonObject.collapseHeight = this.formData.form.collapseHeight
        this.extendJsonObject.collapseLength = this.formData.form.collapseLength
        this.extendJsonObject.collapseWidth = this.formData.form.collapseWidth
        this.extendJsonObject.disposalPhone = this.formData.form.disposalPhone
        this.formData.form.extendJson = JSON.stringify(this.extendJsonObject)
      },
      getExtendJson(extendJson) {
        console.log(extendJson)
        this.extendJsonObject = JSON.parse(extendJson)
        this.formData.form.collapseAcreage = this.extendJsonObject.collapseAcreage
        this.formData.form.collapseVolume = this.extendJsonObject.collapseVolume
        this.formData.form.collapseHd = this.extendJsonObject.collapseHd
        this.formData.form.collapseHeight = this.extendJsonObject.collapseHeight
        this.formData.form.collapseLength = this.extendJsonObject.collapseLength
        this.formData.form.collapseWidth = this.extendJsonObject.collapseWidth
        this.formData.form.disposalPhone = this.extendJsonObject.disposalPhone
      },
      add() {
        this.formData.form.id = null
        this.formData.form.delFlag = 0;
        this.addExtendJson()
        //4 代表上报
        this.formData.form.fromType = '4';

        riskHazardAdd(this.formData.form).then(res => {
          if (res.code == 200) {
            this.$message({
              message: this.$t('tips.createSuccess'),
              type: 'success'
            })
            this.closeSuccess()
          } else {
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        })
      },
      update() {
        this.addExtendJson()
        riskHazardUpdate(this.formData.form).then(res => {
          if (res.code == 200) {
            this.$message({
              message: this.$t('tips.updateSuccess'),
              type: 'success'
            })
            this.closeSuccess()
          } else {
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        })
      },
      cancel() {
        this.close()
      },
      handleClose(done) {
        done()
        this.close()
      },
      closeSuccess() {
        this.$refs.vformComponents.$refs.form.resetFields();
        this.categoryOptions = [];
        this.facilityOptions=[];
        this.$emit('success')
      },
      close(val) {
        this.$refs.vformComponents.$refs.form.resetFields();
        this.categoryOptions = [];
        this.facilityOptions=[];
        if(!val){
          this.$emit('close')
        }
      },
      getData() {

        // 获取字典值
        this.bClassifyOptions = []
        this.$commonJs.filterDataDict("hazardBClassify", this.bClassifyOptions)
        this.formData.form.bclassify = '03'

        this.sClassifyOptions = []
        this.$commonJs.filterDataDict("hazardSClassify", this.sClassifyOptions)
        this.formData.form.sclassify = '008'

        this.categoryOptions = []
        //this.$commonJs.filterDataDict("hazardCategory", this.categoryOptions)

        this.gradeOptions = []
        this.$commonJs.filterDataDict("patrolHazardLevel", this.gradeOptions)

        this.stateOptions = []
        this.$commonJs.filterDataDict("hazardDealState", this.stateOptions)

        if (this.openType != "add") {
          riskHazardDetail(this.id).then(res => {
            if (res.code == 200) {
              console.log(res.data)
              this.formData.form = res.data
              this.getExtendJson(res.data.extendJson)
              this.sendCategoryData();
              this.sendFacilityData();
              this.loadFormat()
              this.positionLoadFormat()
            } else {
              this.$message({
                message: this.$t('tips.systemException'),
                type: 'error'
              })
            }
          })
        }else{
          this.facilityOptions=[];
          this.sendFacilityData();
          this.categoryOptions = [];
          this.sendCategoryData();
        }
      },
    },


  };
</script>

<style lang="scss" scoped>
  .e-dialog-footer{
    padding: 20rem 0 4rem 20rem;
    text-align: right;
    box-sizing: border-box;
  }
</style>

